package com.tuo51.childcare.service.impl;

import com.google.common.collect.ImmutableMap;
import com.tuo51.childcare.domain.bize.*;
import com.tuo51.childcare.domain.feed.Feeds;
import com.tuo51.childcare.domain.vo.BizEvaluateAnswerSheetItemVO;
import com.tuo51.childcare.domain.vo.BizEvaluateQuestionOptionVO;
import com.tuo51.childcare.repository.*;
import com.tuo51.childcare.service.BizEvaluateService;
import com.tuo51.childcare.service.FeedsService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.evaluate.repositories.children.ChildrenRepository;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BizEvaluateServiceImpl implements BizEvaluateService {

    @Autowired
    BizEvaluateSheetRepository sheetRepository;

    @Autowired
    BizEvaluateDimensionRepository dimensionRepository;

    @Autowired
    BizEvaluateDimensionScoreRepository dimensionScoreRepository;

    @Autowired
    BizEvaluateQuestionRepository questionRepository;

    @Autowired
    BizEvaluateRecordRepository recordRepository;

    @Autowired
    ChildrenRepository childrenRepository;

    @Autowired
    ChildrenService childrenService;

    @Autowired
    FeedsRepository feedsRepository;


    public BizEvaluateRecord reportDetail(String staffId, String recordId){
        BizEvaluateRecord ret = recordRepository.getByCreatorIdAndId(staffId, recordId);

        List<BizEvaluateDimensionScore> scores = dimensionScoreRepository.findAllByRecordId(recordId);

        ret.setDimensionScores(scores);

        return ret;
    }

    public List<BizEvaluateSheet> allSupportingSheets(){
        return allSupportingSheets(0);
    }

    public List<BizEvaluateSheet> allSupportingSheets(int userChannel){
        return sheetRepository.findAllByDeletedIsFalse();
    }

    @Override
    public List<BizEvaluateQuestion> questionForSheet(String sheetId) {
        BizEvaluateSheet sheet = sheetRepository.getOne(sheetId);

        if (sheet == null){
            throw new BusinessException(ErrorCode.BIZ_SHEET_NOT_EXIST,  "量表不存在");
        }

        List<BizEvaluateQuestion> ret = questionRepository.findAllBySheetIdAndDeletedIsFalseOrderByIndexOnPaper(sheetId);
        return ret;
    }

    @Override
    public Map defaultSheetQuestions(Staff staff){
        //402847a37433d2bb017433d2ed660000   0-1
        //402847a37433d2bb017433d7556f013e   1-3
        //402847a37433d2bb017433d300750052   3-6
        final String ZERO_YEAR_SHEET_ID = "402847a37433d2bb017433d2ed660000";
        final String ONE_YEAR_SHEET_ID = "402847a37433d2bb017433d7556f013e";
        final String THREE_YEAR_SHEET_ID = "402847a37433d2bb017433d300750052";

        Children c = childrenService.defaultChildrenForParent(staff);

        String sheetId = "";

        if (c.getMonth() < 12){
            sheetId = ZERO_YEAR_SHEET_ID;
        }else if(c.getMonth() < 36){
            sheetId = ONE_YEAR_SHEET_ID;
        }else{
            sheetId = THREE_YEAR_SHEET_ID;
        }

        List<BizEvaluateQuestion> questions = questionForSheet(sheetId);

        Map ret = ImmutableMap.of("sheetId", sheetId, "questions", questions);

        return ret;
    }

    @Override
    public BizEvaluateRecord parseAnswerSheet(Staff staff, String childrenId,
                                       String childrenName,
                                       Integer gender,
                                       String birthday,
                                       String sheetId,
                                       List<BizEvaluateAnswerSheetItemVO> answerSheet){

        BizEvaluateSheet sheet = sheetRepository.getOne(sheetId);
        if (sheet == null) {
            throw new BusinessException(ErrorCode.EVALUATE_JSON_ERROR, "量表没有找到");
        }

        //创建测评对象
        BizEvaluateRecord record = new BizEvaluateRecord();

        if (StringUtils.isNotEmpty(birthday)) {
            record.setMonth((int) (DateUtil.betweenMonthsV2(new Date(), DateUtil.parseToDate(birthday)) + 0.5));
            record.setBirthday(DateUtil.parseToDate(birthday));
        }
        record.setChildrenId(childrenId);
        record.setChildrenName(childrenName);
        record.setCreatorId(staff.getId());
        record.setCreatorName(staff.getRealName());
        record.setTitle(childrenName + "宝宝的" + sheet.getSheetName() + "报告" );
        //
        List<BizEvaluateQuestion> questions = questionRepository.findAllBySheetIdAndDeletedIsFalseOrderByIndexOnPaper(sheetId);

        Map<String , BizEvaluateDimensionScore> dimensionScoreMap = new HashMap<>();

        //创建答题卡缓存
        Map<String, List<BizEvaluateQuestionOptionVO>> answers = new HashMap<>();
        for (BizEvaluateAnswerSheetItemVO item : answerSheet){
            answers.put(item.getQuestionId(), item.getSelections());
        }

        //开始分析得分
        for (BizEvaluateQuestion question : questions){
            String dimensionId = question.getDimensionId();

            BizEvaluateDimension dimension = dimensionRepository.getBySheetIdAndId(sheetId, dimensionId);
            BizEvaluateDimensionScore score = dimensionScoreMap.get(dimensionId);
            if (score == null){
                score =  BizEvaluateDimensionScore.of(record.getId(), dimension.getId(), dimension.getName(), 0, false);
                dimensionScoreRepository.save(score);

                dimensionScoreMap.put(dimensionId, score);
            }

            List<BizEvaluateQuestionOptionVO> options = answers.get(question.getId());

            //保存答案
            //先不保存答案，直接出结果？

            //计算得分
            if (options != null && options.size() > 0)
            for (BizEvaluateQuestionOptionVO option : options){
                double val = score.getScore() + option.getScore() * question.getFactor();
                score.setScore((int)val);
            }
        }

        List<BizEvaluateDimensionScore> scores = new ArrayList<>(dimensionScoreMap.values());

        //计算最终得分
        int result = 0;
        for (BizEvaluateDimensionScore score : scores){
            result += score.getScore();
        }
        //
        record.setScore(result);

        double rating = result * 1.0 / sheet.getMaxScore();
        record.setRating(String.format("%.1f", rating * 100));
        record.setDimensionScores(scores);
        record.setFinished(true);
        record.setPaid(true);
        record.setAdvise(String.format("您的得分超过全国 %.1f%% 的家长", rating * rating));
        recordRepository.save(record);

        scores.stream().forEach(k->k.setRecordId(record.getId()));
        dimensionScoreRepository.saveAll(scores);

        //推送feed
        generateFeeds(staff, record);

        //这里不需要推送

        return record;
    }


    private boolean generateFeeds(Staff user, BizEvaluateRecord record){

        Feeds feeds = Feeds.of(
                record.getTitle(),
                null,
                null,
                record.getChildrenId(),
                record.getChildrenName(),
                record.getGender(),
                FeedsService.FeedsType.BizRecord_GrowupEnv,
                user.getId(),
                record.getId(), record.getCreated());

        feedsRepository.save(feeds);

        return true;
    }
}
